package cn.pupil.springframework.core.convert.support;

import cn.pupil.springframework.core.convert.converter.Converter;
import cn.pupil.springframework.core.convert.converter.ConverterFactory;
import cn.pupil.springframework.util.NumberUtils;
import com.sun.istack.internal.Nullable;

/**
 * @Description: 字符串转换数字的类型转换器工厂
 * @Author: pupil
 * @Date: 2024/12/16 下午 6:25
 */
public class StringToNumberConverterFactory implements ConverterFactory<String,Number> {

    @Override
    public <T extends Number> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToNumber<>(targetType);
    }

    /**
     * 字符串转换数字的类型转换
     * @param <T>
     */
    private static final class StringToNumber<T extends Number> implements Converter<String,T>{

        // 目标类型
        private final Class<T> targetType;

        public StringToNumber(Class<T> targetType) {
            this.targetType = targetType;
        }


        @Override
        @Nullable
        public T convert(String source) {
            if (source.isEmpty()){
                return null;
            }
            return NumberUtils.parseNumber(source, this.targetType);
        }
    }
}
